package com.deanlib.cabinet.data.network;


import android.content.Context;

import com.deanlib.cabinet.app.Constants;
import com.deanlib.cabinet.data.network.intercept.AuthInterceptor;
import com.deanlib.cabinet.data.network.intercept.DynamicAnnotationInterceptor;
import com.deanlib.cabinet.data.network.request.Request;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Zaifeng on 2018/2/28.
 * Modify by Dean on 2021/6/28
 * API初始化类
 */

public class NetWorkManager {

    private static NetWorkManager mInstance;
    private static Retrofit retrofit;
    private static PersistentCookieStore cookieStore;
    private static volatile Request request = null;

    public static NetWorkManager getInstance() {
        if (mInstance == null) {
            synchronized (NetWorkManager.class) {
                if (mInstance == null) {
                    mInstance = new NetWorkManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化必要对象和参数
     */
    public void init(Context context) {

        //持久化
        cookieStore = new PersistentCookieStore(context);

        //初始化Cookie管理器
        CookieJar cookieJar = new CookieJar() {
            //Cookie缓存区
//            private final Map<String, List<Cookie>> cookiesMap = new HashMap<String, List<Cookie>>();

            @Override
            public void saveFromResponse(HttpUrl arg0, List<Cookie> arg1) {
                //移除相同的url的Cookie
//                String host = arg0.host();
//                List<Cookie> cookiesList = cookiesMap.get(host);
//                if (cookiesList != null){
//                    cookiesMap.remove(host);
//                }
//                //再重新添加
//                cookiesMap.put(host, arg1);
                //存入本地
                if (!arg1.isEmpty()) {
                    for (Cookie cookie : arg1) {
                        cookieStore.add(arg0, cookie);
                    }
                }
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl arg0) {
//                List<Cookie> cookiesList = cookiesMap.get(arg0.host());
//                if (cookiesList == null){
                List<Cookie> cookiesList = cookieStore.get(arg0);
                if (cookiesList == null) {
                    //没有，创建一个
                    //注：这里不能返回null，否则会报NULLException的错误。
                    //原因：当Request 连接到网络的时候，OkHttp会调用loadForRequest()
                    cookiesList = new ArrayList<Cookie>();
                }
//                }
                return cookiesList;
            }
        };

        // 初始化okhttp
        OkHttpClient client = new OkHttpClient.Builder().cookieJar(cookieJar)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(new DynamicAnnotationInterceptor())
                .addInterceptor(new AuthInterceptor())
                .build();

        // 初始化Retrofit
        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(Constants.HOST)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .create()))
                .build();

    }

    public static Request getRequest() {
        if (request == null) {
            synchronized (Request.class) {
                request = retrofit.create(Request.class);
            }
        }
        return request;
    }

    public static void clearCookie(){
        if (cookieStore!=null){
            cookieStore.removeAll();
        }
    }

}
